﻿/*
* Retrieve data from service
**/
function RetrieveData() {
    ClearView();
    $.ajax({
        type: "GET",
        async: false,
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: "/CarService.svc/Cars",
        success: RetrieveMultipleCallback,
        error: function () {
            alert("Error");
        },
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json;odata=verbose");
        }
    });
}

/*
* Handles the RetrieveMultiple Response
**/
function RetrieveMultipleCallback(data) {
    var $newDiv;
    $.each(data.d, function (i, item) {
        $newDiv = $("<div class=\"entry\">" +
                        "<div>" + item.Id + " - " + item.Manufacturer + " - " + item.ProductionYear + "</div>" +
                        "<div class=\"entry_delete\"><input id=\"DeleteButton\" type=\"button\" value=\"Delete\" onclick=\"DeleteData(" + item.Id + ")\" /> </div>" +
                    "</div>");
        $("#listofcars").append($newDiv);
    });
    $newDiv = $("<div>----</div>");
    $("#listofcars").append($newDiv);
}





/*
* Create data by service
**/
function CreateData(id) {
    var car = {};

    var man = $("#man_id").val();
    var year = $("#year_id").val();

    car.Manufacturer = man;
    car.ProductionYear = year;

    var carStringified = JSON.stringify(car);

    $.ajax({
        type: "POST",
        async: false,
        data: carStringified,
        contentType: "application/json",
        datatype: "json",
        url: "/CarService.svc/Cars",
        success: CreateCallback,
        error: function () {
            alert("Error");
        },
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        }
    });
}

/*
* Handles the Create Response
**/
function CreateCallback(data) {
    $("#man_id").val("");
    $("#year_id").val("");
    RetrieveData();
}





/*
* Delete data by service
**/
function DeleteData(data) {
    $.ajax({
        type: "DELETE",
        async: false,
        //data: carStringified,
        contentType: "application/json",
        datatype: "json",
        url: "/CarService.svc/Cars(" + data + ")",
        success: DeleteCallback,
        error: function () {
            alert("Error");
        },
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        }
    });
}

/*
* Handles the Delete Response
**/
function DeleteCallback(data) {
    RetrieveData();
}





/*
* Clears the entry-view
**/
function ClearView() {
    $("#listofcars").empty();
}